<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>计算属性</title>
</head>

<body>
    <p>当模板逻辑复杂时，应当使用计算属性。</p>
    <div id="app">
        <p>{{message.split('').reverse().join('')}}</p>
        <p style="background-color: #ccc;">message.split('').reverse().join('')</p>
        <hr style="width: 100%;height: 2px;border: none;border-top: 2px dashed #000;">
        <h1>1.基础例子</h1>
        <p>Original message: "{{ message }}"</p>
        <p>Computed reversed message: "{{ reversedMessageCom }}"</p>
        <hr style="width: 100%;height: 2px;border: none;border-top: 2px dashed #000;">
        <h1>2.计算缓存 vs Methods</h1>
        <p>Reversed message: "{{ reversedMessageFun() }}"</p>
        <p>Reversed message: "{{ reversedMessageCom }}"</p>
        <p>Method now: "{{ now() }}"</p>
        <p>Computed now: "{{ nowCom }}"</p>
        <hr style="width: 100%;height: 2px;border: none;border-top: 2px dashed #000;">
        <h1>3.计算属性 vs Watched Property</h1>
        <div id="demo">{{ fullName }}</div>
        firstName:<input type="text" v-model="firstName" name="">
        lastName:<input type="text" v-model="lastName" name="">
        <hr style="width: 100%;height: 2px;border: none;border-top: 2px dashed #000;">
        <h1>4.计算 setter</h1>
        见3的代码FulName
    </div>
    <script type="text/javascript" src="../lib/vue.js"></script>
    <script type="text/javascript">
    var app = new Vue({
        el: "#app",
        data: {
            message: 'hello world',
            firstName: 'Foo',
            lastName: 'Bar',
            // fullName: 'Foo Bar'
        },
        methods: {
            reversedMessageFun: function() {
                return this.message.split('').reverse().join('')
            },
            now: function() {
                return Date.now()
            }
        },
        //当数据发生变化时回调watch方法
        watch: {
            firstName: function(val) {
                this.fullName = val + ' ' + this.lastName
            },
            lastName: function(val) {
                this.fullName = this.firstName + ' ' + val
            }
        },
        computed: {
            reversedMessageCom: function() {
                return this.message.split('').reverse().join('')
            },
            nowCom: function() {
                return Date.now()
            },
            fullName:{
            	//getter
            	get:function(){
            		return this.firstName + ' ' + this.lastName
            	},
            	//setter
            	set:function(newValue){
            		var names = newValue.split(' ')
            		this.firstName = names[0]
            		this.lastName = names[names.length - 1]
            	}
            }

        }
    })
    </script>
</body>

</html>
